package com.ruoyi.controller.open;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.dto.DownloadVideoDTO;
import com.ruoyi.common.utils.file.FtpUtils;
import com.ruoyi.config.BsFtpConfig;
import com.ruoyi.hkCamera.service.VideoService;
import com.ruoyi.model.bs.BsUploadDataItem;
import com.ruoyi.model.bs.BsUploadDataReq;
import com.ruoyi.system.domain.FltBsApiLog;
import com.ruoyi.system.service.IFltBsApiLogService;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/open/bs/")
public class BsOpenController extends BaseController {

    @Autowired
    private IFltBsApiLogService ftlBsApiLogService;

    @Autowired
    private VideoService videoService;

    @Autowired
    private BsFtpConfig bsFtpConfig;

    @PostMapping("/importSendLog")
    public AjaxResult importLog(MultipartFile file) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream(), "GBK"));
        String line;
        List<FltBsApiLog> recordList = new ArrayList<>();
        while ((line = br.readLine()) != null) {
            String data = StrUtil.subAfter(line, "======开始上传称重数据到治超平台:", false);
            if (StrUtil.isNotEmpty(data)) {
                BsUploadDataReq bsUploadDataReq;
                try {
                    bsUploadDataReq = JSONUtil.toBean(data, BsUploadDataReq.class);
                } catch (Exception ex) {
                    continue;
                }
                List<BsUploadDataItem> dataContentList = bsUploadDataReq.getDataContent();
                for (BsUploadDataItem dataItem : dataContentList) {
                    double overRate = dataItem.getOverRate();
                    if (overRate > 0) {
                        FltBsApiLog fltBsApiLog = new FltBsApiLog();
                        fltBsApiLog.setSiteId(dataItem.getSiteId());
                        fltBsApiLog.setLaneNo(dataItem.getEquipId());
                        fltBsApiLog.setCheckNo(dataItem.getCheckNo());
                        fltBsApiLog.setVehicleNo(dataItem.getVehicleNo());
                        fltBsApiLog.setCheckTime(DateUtil.date(dataItem.getCheckTime()));
                        recordList.add(fltBsApiLog);
                    }
                }
            }
        }
        ftlBsApiLogService.insertBeach(recordList);
        br.close();
        return success(recordList.size());
    }

    @PostMapping("/downloadVideo")
    public AjaxResult downloadVideo(@RequestBody FltBsApiLog fltBsApiLog) {
        String localPath = RuoYiConfig.getVideoPath() + fltBsApiLog.getSiteId() + "/";//本地视频目录
        List<FltBsApiLog> apiLogList = ftlBsApiLogService.selectList(fltBsApiLog);
        for (FltBsApiLog bsApiLog : apiLogList) {
            String videoDirs = this.getVideoDirs(bsApiLog.getLaneNo(), bsApiLog.getCheckTime());
            DownloadVideoDTO dto = new DownloadVideoDTO();
            dto.setCheckNo(bsApiLog.getCheckNo());
            dto.setLaneNo(bsApiLog.getLaneNo());
            dto.setCheckTime(bsApiLog.getCheckTime());
            dto.setVideoName(bsApiLog.getCheckNo() + "-81" + ".mp4");
            dto.setVideoDirs(localPath + videoDirs);
            // 创建Path对象
            Path path = Paths.get(dto.getVideoDirs() + dto.getVideoName());
            // 检查文件是否存在
            if (!Files.exists(path)) {
                videoService.downloadVideo(dto);
            }
        }
        return success();
    }

    @PostMapping("/ftpVideo")
    public AjaxResult ftpVideo(@RequestBody FltBsApiLog bsApiLog) {
        String localDir = RuoYiConfig.getVideoPath() + bsApiLog.getSiteId() + "/";//本地视频目录

        String laneNos = bsApiLog.getLaneNos();
        String dateDirties = bsApiLog.getDateDirties();

        StrUtil.split(laneNos, ",").forEach(laneNo -> StrUtil.split(dateDirties, ",").forEach(dateDirs -> {
            FTPClient ftpClient = FtpUtils.connection(bsFtpConfig.getIp(), bsFtpConfig.getPort(), bsFtpConfig.getUsername(), bsFtpConfig.getPassword());
            if (ftpClient != null) {
                String videoDir = this.getVideoDirs(laneNo, dateDirs);
                FtpUtils.uploadFolder(ftpClient, localDir + videoDir, videoDir);
                ThreadUtil.sleep(3000);
            }
        }));

        return success();
    }

    private String getVideoDirs(String laneNo, Date checkTime) {
        String dateDirs = DateUtil.format(checkTime, "yyyy/MM/dd");
        return laneNo + "/" + dateDirs + "/";
    }

    private String getVideoDirs(String laneNo, String dateDirs) {
        return laneNo + "/" + dateDirs + "/";
    }
}
